var express = require('express');
var router = express.Router();
var moment = require('moment');
var os = require('os');
let upload = require('../util/multer/index')
let { formateDate, urlf2z, urlf2zList, getPerformer, FormatData } = require('../util.js');
let { isAdminLogin, getAdminList, getUserList, setUserState, delUser, getRegionList, addRegion, getRegionById, delRegion, updateRegion, getIndexCount,
  getUserListWord, getRegionTable
} = require('../mysql/index');


router.post('/isAdminLogin', async (req, res, next) => {
  let { username, password, code } = req.body;
  // try {
  //   const sessionCaptcha = req.session.captcha.toLowerCase();
  //   if (sessionCaptcha != code) {
  //     return res.json({
  //       flog: 0,
  //       data: '验证码不正确'
  //     });
  //   }
  // } catch (error) {
  //   return res.json({
  //     flog: 0,
  //     data: '验证码不正确'
  //   });
  // }
  let data = await isAdminLogin({
    username,
    password
  });
  if (!data.length) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误"
    }
  } else {
    jsonData = {
      code: 1,
      data: {
        "username": username,
        "adminId": data[0].id,
        url: data[0].url
      }
    }
    req.session.AdminInfo = {
      username: username,
      adminId: data[0].id
    }
  }
  return res.json(jsonData)
});

router.get('/getAdminList', async (req, res, next) => {
  let { page, limit } = req.query;
  var num = (page - 1) * limit;
  let { data, count } = await getAdminList(num, limit, {
  });
  res.json({
    code: 0,
    data: data,
    count: count
  })
})

router.get('/getUserList', async (req, res, next) => {
  let { page, limit, userId, userName, userSex, isusing } = req.query;
  var num = (page - 1) * limit;
  let { data, count } = await getUserList(num, limit, {
    userId, userName, userSex, isusing
  });
  res.json({
    code: 0,
    data: data,
    count: count
  })
})

router.post('/userState', async (req, res, next) => {
  let { userId, isusing } = req.body;
  console.log(userId, isusing)
  let { affectedRows } = await setUserState(userId, {
    isusing: isusing
  })
  if (affectedRows) {
    res.json({
      code: 1
    })
  } else {
    res.json({
      code: 0,
      msg: "修改失败 "
    })
  }
})

router.post('/delUser', async (req, res, next) => {
  let { userId } = req.body;
  let { affectedRows } = await delUser(userId)
  if (affectedRows) {
    res.json({
      code: 1
    })
  } else {
    res.json({
      code: 0,
      msg: '删除失败'
    })
  }
})

router.get('/getRegionList', async (req, res, next) => {
  let { page, limit, regionId, regionState } = req.query;
  var num = (page - 1) * limit;
  let { data, count } = await getRegionList(num, limit, {
    regionId, regionState
  });
  res.json({
    code: 0,
    data: FormatData(data, {
      'regionImgs': 'json',
      'regionDate': 'date'
    }),
    count: count
  })
})

router.post('/addRegion', upload.array('regionImg', 10), async (req, res, next) => {
  let { regionName, regionPrice, regionIntroduce, regionDate, regionState } = req.body;
  let regionImgs = urlf2zList(req);
  await addRegion({
    regionName, regionPrice, regionIntroduce, regionDate, regionState,
    regionImgs: JSON.stringify(regionImgs)
  })
  res.json({
    code: 1,
    data: "添加成功"
  })
})

router.post('/getRegionById', async (req, res, next) => {
  let { regionId } = req.body;
  let data = await getRegionById(regionId);
  res.json({
    code: 0,
    data: FormatData(data, {
      'regionImgs': 'json',
      'regionDate': 'date'
    })
  })
})

router.post('/delRegion', async (req, res, next) => {
  let { regionId } = req.body;
  let { affectedRows } = await delRegion(regionId)
  if (affectedRows) {
    res.json({
      code: 1
    })
  } else {
    res.json({
      code: 0,
      msg: '删除失败'
    })
  }
})

router.post('/updateRegion', upload.array('regionImg', 10), async (req, res, next) => {
  let { regionName, regionPrice, regionIntroduce, regionDate, regionState, regionId, srcArr } = req.body;
  let regionImgs = urlf2zList(req);
  srcArr = JSON.parse(srcArr);
  regionImgs = srcArr.concat(regionImgs);
  await updateRegion(regionId, {
    regionName, regionPrice, regionIntroduce, regionDate, regionState,
    regionImgs: JSON.stringify(regionImgs)
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getIndexCount', async (req, res, next) => {
  let [{ userNum }, { adminNum }, { regionNum }, { orderNum }] = await getIndexCount()
  res.json({
    code: 1,
    adminNum, regionNum, orderNum, userNum
  })
})

router.get('/getuserNumTable', async (req, res, next) => {
  let DayList = [];
  for (var i = 1; i <= 7; i++) {
    DayList.push(moment().isoWeekday(i))
  }
  let { count, data } = await getUserListWord();
  let userNum = []

  DayList.forEach(dayItem => {
    let sunNum = 0;
    data.forEach(item => {
      if (dayItem.isSame(item.userTime, 'day')) {
        sunNum++;
      }
    })
    userNum.push(sunNum)
  })

  res.json({
    code: 1,
    userNum: userNum,
    count: count
  })

});

router.get('/getCpuTable', async (req, res, next) => {
  var freeMem = os.freemem() / 1024 / 1024 / 1024;
  var totalMem = os.totalmem() / 1024 / 1024 / 1024;
  res.json({
    code: 1,
    CpuNum: ((freeMem) / totalMem * 100.0).toFixed(2)
  })
})

router.get('/getRegionTable', async (req, res, next) => {
  let typeList = ['使用中', '已预约', '空闲'];
  let data = await getRegionTable(typeList);
  data = JSON.parse(JSON.stringify(data))
  data = data.map(item => {
    return item[0]
  })
  res.json({
    code: 1,
    typeList,
    seriesData: data
  })
})
module.exports = router;